<template>
  <div id="app">
    <div class="container">
      <header class="header">
        <h1 class="title">📝 我的待办清单</h1>
        <p class="subtitle">今日事，今日毕</p>
      </header>

      <main class="main">
        <AddTodo @add-todo="addTodo" />
        
        <div class="todo-stats">
          <span>总计: {{ totalTodos }} 个任务</span>
          <span>已完成: {{ completedTodos }} 个</span>
          <span>待完成: {{ activeTodos }} 个</span>
        </div>

        <TodoFilter 
          :filter="currentFilter"
          @update-filter="updateFilter"
        />

        <TodoList
          :todos="filteredTodos"
          @toggle-todo="toggleTodo"
          @delete-todo="deleteTodo"
          @edit-todo="editTodo"
        />
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import AddTodo from './components/AddTodo.vue'
import TodoList from './components/TodoList.vue'
import TodoFilter from './components/TodoFilter.vue'

const todos = ref([])
const currentFilter = ref('all')

// 从 localStorage 加载数据
const loadTodos = () => {
  const saved = localStorage.getItem('vue-todos')
  if (saved) {
    todos.value = JSON.parse(saved)
  }
}

// 保存到 localStorage
const saveTodos = () => {
  localStorage.setItem('vue-todos', JSON.stringify(todos.value))
}

// 添加新任务
const addTodo = (text) => {
  if (text.trim()) {
    const newTodo = {
      id: Date.now(),
      text: text.trim(),
      completed: false,
      createdAt: new Date().toLocaleString()
    }
    todos.value.unshift(newTodo)
  }
}

// 切换任务状态
const toggleTodo = (id) => {
  const todo = todos.value.find(t => t.id === id)
  if (todo) {
    todo.completed = !todo.completed
  }
}

// 删除任务
const deleteTodo = (id) => {
  todos.value = todos.value.filter(t => t.id !== id)
}

// 编辑任务
const editTodo = (id, newText) => {
  const todo = todos.value.find(t => t.id === id)
  if (todo && newText.trim()) {
    todo.text = newText.trim()
  }
}

// 更新过滤器
const updateFilter = (filter) => {
  currentFilter.value = filter
}

// 计算属性
const totalTodos = computed(() => todos.value.length)
const completedTodos = computed(() => todos.value.filter(t => t.completed).length)
const activeTodos = computed(() => totalTodos.value - completedTodos.value)

const filteredTodos = computed(() => {
  switch (currentFilter.value) {
    case 'active':
      return todos.value.filter(todo => !todo.completed)
    case 'completed':
      return todos.value.filter(todo => todo.completed)
    default:
      return todos.value
  }
})

// 监听数据变化并保存
watch(todos, saveTodos, { deep: true })

// 初始化加载数据
onMounted(loadTodos)
</script>